import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:efood_multivendor/controller/auth_controller.dart';
import 'package:efood_multivendor/controller/cart_controller.dart';
import 'package:efood_multivendor/controller/localization_controller.dart';
import 'package:efood_multivendor/controller/location_controller.dart';
import 'package:efood_multivendor/controller/order_controller.dart';
import 'package:efood_multivendor/controller/product_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/controller/user_controller.dart';
import 'package:efood_multivendor/helper/route_helper.dart';
import 'package:efood_multivendor/helper/size_config.dart' as Size;
import 'package:efood_multivendor/helper/version_converter.dart';
import 'package:efood_multivendor/util/app_constants.dart';
import 'package:efood_multivendor/util/images.dart';
import 'package:efood_multivendor/view/base/no_internet_screen.dart';
import 'package:efood_multivendor/view/screens/auth/sign_up_screen.dart';

import 'package:efood_multivendor/view/screens/update/update_screen.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:in_app_update/in_app_update.dart';

class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen>
    with WidgetsBindingObserver {
  GlobalKey<ScaffoldState> _globalKey = GlobalKey();
  StreamSubscription<ConnectivityResult>? _onConnectivityChanged;

  @override
  void initState() {
    super.initState();
    try {
      bool _firstTime = true;
      _onConnectivityChanged = Connectivity()
          .onConnectivityChanged
          .listen((ConnectivityResult result) {
        if (!_firstTime) {
          bool isNotConnected = result != ConnectivityResult.wifi &&
              result != ConnectivityResult.mobile;
          isNotConnected
              ? SizedBox()
              : ScaffoldMessenger.of(context).hideCurrentSnackBar();
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(
            backgroundColor: isNotConnected ? Colors.red : Colors.green,
            duration: Duration(seconds: isNotConnected ? 6000 : 3),
            content: Text(
              isNotConnected ? 'no_connection'.tr : 'connected'.tr,
              textAlign: TextAlign.center,
            ),
          ));
          if (!isNotConnected) {
            _route();
          }
        }
        _firstTime = false;
      });

      Get.find<SplashController>().initSharedData();
      Get.find<CartController>().getCartData();
      Get.find<CartController>().clearCartList();
      Get.find<LocalizationController>().fetchLocalStoredAddressName();

      // checkForUpdate();
    } finally {
      WidgetsBinding.instance.addObserver(this);
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        _route();
      });
    }
  }

  Future<void> checkForUpdate() async {
    InAppUpdate.checkForUpdate().then((info) async {
      if (info.updateAvailability == UpdateAvailability.updateAvailable) {
        await InAppUpdate.startFlexibleUpdate().then((_) {});
        await InAppUpdate.completeFlexibleUpdate().then((_) {});
      }
    }).catchError((error) {});
  }

  @override
  void dispose() {
    super.dispose();
    _onConnectivityChanged?.cancel();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    if (state == AppLifecycleState.resumed) {
      //  Get.find<LocationController>().getCurrentLocation(false, notify: false);
    } else if (state == AppLifecycleState.paused) {
      print('App moved to background');
    }
  }

  int configRetryCount = 1;

  void _route() {
    if (configRetryCount >= 3) {
      return;
    }
    Get.find<SplashController>().getConfigData().then((isSuccess) {
      if (!isSuccess) {
        configRetryCount++;
        _route();
        return;
      }
      if (isSuccess) {
        Timer(Duration(seconds: 1), () async {
          String _minimumVersion = '';

          if (GetPlatform.isAndroid) {
            _minimumVersion = Get.find<SplashController>()
                    .configModel
                    ?.appMinimumVersionAndroid ??
                '';
          } else if (GetPlatform.isIOS) {
            _minimumVersion = Get.find<SplashController>()
                    .configModel
                    ?.appMinimumVersionIos ??
                '';
          }
          if (VersionConvertor.compareVersions(
              Get.find<SplashController>().currentVersion!, _minimumVersion)) {
            Get.offNamed(RouteHelper.getUpdateRoute(true));
          } else if (Get.find<SplashController>().configModel?.emergencyMode ==
              1) {
            Get.off(UpdateScreen(isUpdate: false, isEmergency: true));
          } else {
            if (Get.find<AuthController>().isLoggedIn()) {
              try {
                await Get.find<LocationController>().getAddressList();
                await Get.find<ProductController>().getUnreviewedOrdersData();

                if (Get.find<ProductController>()
                            .unreviewedOrdersResponse
                            ?.reviewOrders !=
                        null &&
                    Get.find<ProductController>()
                            .unreviewedOrdersResponse
                            ?.reviewOrders
                            ?.isNotEmpty ==
                        true) {
                  Get.find<OrderController>().getOrderDetails(
                      Get.find<ProductController>()
                          .unreviewedOrdersResponse!
                          .reviewOrders![0]
                          .id
                          .toString());
                }
                // if (Get.find<LocationController>().addressList.length == 0) {
                //   SharedPreferences prefrences =
                //       await SharedPreferences.getInstance();
                //   await prefrences.remove(AppConstants.HOME_LOCATION);
                //   await prefrences.remove(AppConstants.workLocation);
                // }
              } catch (e) {}

              if (Get.find<UserController>().userInfoModel != null &&
                  Get.find<UserController>().userInfoModel?.fName != null &&
                  Get.find<UserController>().userInfoModel?.fName ==
                      "Not Set") {
                Get.to(SignUpScreen());
              } else {
                // if (Get.find<SplashController>()
                //         .configModel
                //         .deadzoneAvailableOrder ==
                //     1) {
                Get.toNamed(RouteHelper.getInitialRoute("SplashScreen"));
                //   } else {

                // int timestamp;
                // int minuites = 20;
                // final prefs = await SharedPreferences.getInstance();
                // timestamp = prefs.getInt('LocationTimestamp');

                // if (timestamp != null) {
                //   DateTime before =
                //       DateTime.fromMillisecondsSinceEpoch(timestamp);
                //   DateTime now = DateTime.now();
                //   Duration timeDifference = now.difference(before);
                //   minuites = timeDifference.inMinutes;
                // }
                // if (minuites > 15) {
                //   Get.toNamed(RouteHelper.getInitialRoute(""));
                // } else {
                //   HomeScreen.loadData(false).catchError((e) {});
                //   Get.toNamed(RouteHelper.getInitialRoute("SplashScreen"));
                // }
                // }
              }
            } else {
              if (Get.find<SplashController>().showIntro()) {
                if (AppConstants.languages.length > 1) {
                  Get.offNamed(RouteHelper.getLanguageRoute('splash'));
                } else {
                  Get.offNamed(RouteHelper.getOnBoardingRoute());
                }
              } else {
                Get.offNamed(RouteHelper.getSignInRoute(RouteHelper.splash));
              }
            }
          }
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    Size.init(context);

    return Stack(children: <Widget>[
      Container(
        color: Colors.white,
        child: Image.asset(
          Images.pattern_bg,
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          fit: BoxFit.cover,
        ),
      ),
      Scaffold(
        key: _globalKey,
        backgroundColor: Colors.transparent,
        body: GetBuilder<SplashController>(builder: (splashController) {
          return splashController.hasConnection
              ? Align(
                  alignment: Alignment.bottomCenter,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Image.asset(Images.logo, width: 150),
                      SizedBox(height: height * 0.2),
                      CircularProgressIndicator.adaptive(
                        backgroundColor:
                            Theme.of(context).colorScheme.secondary,
                      ),
                      SizedBox(
                        height: height * 0.05,
                      ),
                      Image.asset(Images.name, width: 150),
                      SizedBox(height: height * 0.08),
                    ],
                  ),
                )
              : NoInternetScreen(child: SplashScreen());
        }),
      )
    ]);
  }
}
